package com.yonyou.iuap.jxzy.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;



import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import bsh.This;

import com.yonyou.iuap.base.web.BaseController;
import com.yonyou.iuap.generic.adapter.impl.InvocationInfoProxy;
import com.yonyou.iuap.jxzy.dao.AcceptancePaperMapper;
import com.yonyou.iuap.jxzy.entity.AcceptancePaper;
import com.yonyou.iuap.jxzy.service.AcceptancePaperService;
import com.yonyou.iuap.mvc.type.SearchParams;


/**
 * 说明：国内废纸验收
 * @author Junxiang Peng
 * 
 */

@Controller
@RequestMapping(value="/jx_acceptancePaper")
public class AcceptancePaperController extends BaseController{

	private Logger logger = LoggerFactory.getLogger(AcceptancePaperController.class);
	
	private AcceptancePaperService acceptancePaperService;
	
	

    @Autowired
    public void setAcceptancePaperService(AcceptancePaperService acceptancePaperService) {
        this.acceptancePaperService = acceptancePaperService;
    }
    
    @Autowired
    private AcceptancePaperMapper mapper;
	
	 @RequestMapping(value = "/list")
	    @ResponseBody
	    public Object list(PageRequest pageRequest, SearchParams searchParams) {
		 Map<String, Object> searchMap = searchParams.getSearchMap();
	    	if(searchMap.get("pk_material")!=null){
	    		String string = searchMap.get("pk_material").toString();
	    		searchMap.put("pk_material", string.replace(",", "','"));
	    	}
	    	if(searchMap.get("checkPointpk")!=null){
	    		String string1 = searchMap.get("checkPointpk").toString();
	    		searchMap.put("checkPointpk", string1.replace(",", "','"));
	    	}
	        Page<AcceptancePaper> page = this.acceptancePaperService.selectAllByPage(pageRequest, searchParams);
	        Map<String, Object> map = new HashMap<String, Object>();
	        map.put("data", page);
	        return this.buildMapSuccess(map);
	    }
	 
	 /**
	  * 根据时间查询获取数据
	  * @param request
	  * @param response
	  * @param searchParams
	  * @return
	  */
	 @RequestMapping(value="/list-param")
	 @ResponseBody
	 public Object listParam(@RequestParam String startTime,String endTime,String usrcode,String serialNo){
		 JSONObject jsonObject=new JSONObject();
		 try {
			 List<AcceptancePaper> listParam =acceptancePaperService.findByTime(startTime,endTime,usrcode,serialNo);
			// Set set=acceptancePaperService.findByTime(startTime,endTime,usrcode,serialNo);
			 return this.buildSuccess(listParam);
			
		} catch (Exception e) {
			jsonObject.put("message", "查询国内废纸验收异常："+e.getMessage());
			jsonObject.put("success", "error");
		}
		 return jsonObject.toString();
	 }
	 /**
	  * 新增国内废纸APP
	  * @param acceptancePaper
	  * @param request
	  * @param response
	  * @return
	  */
	 @RequestMapping(value="/save-param",method={RequestMethod.POST})
	 @ResponseBody
	 public Object insertParam(@RequestBody String acceptancePaper,HttpServletRequest request,HttpServletResponse response){
		 JSONObject jsonObject= JSONObject.fromObject(acceptancePaper);
		 AcceptancePaper acPaper=(AcceptancePaper)JSONObject.toBean(jsonObject, AcceptancePaper.class);
		 JSONObject js=new JSONObject();
		 try {
			 this.acceptancePaperService.insertAndCheckout(acPaper);
			//保存当时价格
			//this.acceptancePaperService.mergeSerialUnit(acPaper);
			this.acceptancePaperService.iii(acPaper);
		} catch (Exception e) {
			js.put("message", e.getMessage());
			js.put("success", "error"); 
			logger.error("提交失败:"+e.getMessage());
			return js.toString();
		}
		 return this.buildSuccess("提交成功！");
		
	 }

	 /**
	  * web页面详细详细
	  * @param request
	  * @param response
	  * @return
	  */
	 @RequestMapping(value="/childlist",method={RequestMethod.GET})
	 @ResponseBody
	 public Object getChildList(PageRequest pageRequest,SearchParams searchParams){
		 Page<AcceptancePaper> page = acceptancePaperService.getChildListById(pageRequest, searchParams);
		 for (AcceptancePaper acPaper:page) {
				String imgUrl=acPaper.getImgUrl();
				if (imgUrl!=null) {
					String[] imgurls=imgUrl.split(",");
					acPaper.setImgUrls(imgurls);
				}
			}
	        Map<String, Object> map = new HashMap<String, Object>();
	        map.put("data", page);
	        return this.buildMapSuccess(map);
		
	 }
	 /**
	  * 根据物料品种获取质量等级
	  * @param acceptancePaper
	  * @param request
	  * @param response
	  * @return
	  */
	 @RequestMapping(value="/get-quality-grade",method={RequestMethod.GET})
	 @ResponseBody
	 public Object getQualityGrade(String pk_org){
		 JSONObject jsonObject= new JSONObject();
		 
		 try {
			 List<String> qualityGtadeList=acceptancePaperService.getQualityGrade(pk_org);
			 return this.buildSuccess(qualityGtadeList);
		} catch (Exception e) {
			jsonObject.put("message", "查询质量等级异常："+e.getMessage());
			jsonObject.put("success", "error");
		}
		 return jsonObject.toString();
		
	 }
	 
	 /**
	  * 根据物料品种和质量等级 获取单价
	  * @param 
	  * @param request
	  * @param response
	  * @return
	  */
	 @RequestMapping(value="/get-unit",method={RequestMethod.GET})
	 @ResponseBody
	 public Object getUnit(String materialVariety,String sysId,String qualityGrade){
		 JSONObject jsonObject= new JSONObject();
		 
		 try {
			 Map<String, Object> unit=acceptancePaperService.getUnit(materialVariety,qualityGrade);
			 HashMap<String, Object> result = new HashMap<String, Object>();
			 Set<String> keySet = unit.keySet();
			 for (String s : keySet) {
				 String lowerCase = s.toLowerCase();
				 result.put(lowerCase, unit.get(s));
			}
			 return this.buildSuccess(result);
		} catch (Exception e) {
			jsonObject.put("message", "查询质量等级异常："+e.getMessage());
			jsonObject.put("success", "error");
		}
		 return jsonObject.toString();
		
	 }
	 /**
	  * 是否重检 
	  * 1.如果该磅单已完成，则不允许修改
	  * 2.修改完后，根据id和序列号，该条数据为1（根据条件设置为1的数据不展示），新增的数据设置为0
	  * 序列号获取磅单表的完成状态
	  * 3.获取当前操作重检人的姓名
	  */
	 @RequestMapping(value="/confirmVerify",method={RequestMethod.POST})
	 @ResponseBody
	 public Object booleanCheck(@RequestBody AcceptancePaper acceptancePaper,HttpServletRequest request){
		 JSONObject json=new JSONObject();
		 String modifierReason= acceptancePaper.getModifierReason();
		 String serialNo=acceptancePaper.getSerialNo();
		String id=acceptancePaper.getId();
		
		String userName=null;
		Cookie[]  cookies=request.getCookies();
		if (cookies!=null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("_A_P_userLoginName")) {
                	userName = cookie.getValue();
                }
            }
		}
		logger.error("测试cookies获取当前用户名称："+userName+modifierReason+serialNo);
		try {
			
					 this.acceptancePaperService.booleanCheck(id,modifierReason,serialNo,userName);
		} catch (Exception e) {
			json.put("success", "error");
			json.put("message", "重检失败：原因是"+e.getMessage());
			return json.toString();
		}
		
		 return this.buildSuccess("重检成功");
	 }
	 
//	 @RequestMapping(value = "/getimpurityrabge",method = {RequestMethod.GET})
//	 @ResponseBody
//	 public String getImpurityRange(String materialVariety,String sysId,String qualityGrade){
//		 
//	 }
	 
}
